<!-- src/layouts/BasicLayout.vue -->
<template>
  <el-container 
    class="layout-container" 
    :class="`layout-${appStore.settings.Layout}`"
  >
    <!-- 垂直布局 - 左侧菜单 -->
    <template v-if="appStore.settings.Layout === 'vertical'">
      <el-aside 
        v-if="!appStore.settings.HiddenSideBar" 
        :width="sidebarWidth" 
        class="sidebar-container"
      >
        <!-- Logo -->
        <div class="logo">
          <div class="logo-icon">
            <svg viewBox="0 0 24 24" fill="currentColor" class="logo-svg">
              <path d="M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z"/>
            </svg>
          </div>
          <transition name="fade">
            <div v-if="appStore.sidebar.opened" class="logo-text">
              <span class="logo-title">{{ appStore.settings.Title }}</span>
              <span class="logo-subtitle">管理系统</span>
            </div>
          </transition>
        </div>
        <Sidebar />
      </el-aside>

      <el-container class="main-container">
        <el-header class="header">
          <Header />
        </el-header>
        <TabsView v-if="!appStore.settings.HideTabs" />
        <el-main ref="mainContentRef" class="main-content" @scroll="handleScroll">
          <div class="content-wrapper">
            <router-view v-slot="{ Component, route }">
              <transition name="fade-transform" mode="out-in">
                <keep-alive v-if="appStore.settings.KeepAlive" :include="cachedViews">
                  <component :is="Component" :key="route.path" />
                </keep-alive>
                <component v-else :is="Component" :key="route.path" />
              </transition>
            </router-view>
          </div>
        </el-main>
      </el-container>
    </template>

    <!-- 水平布局 - 顶部菜单 -->
    <template v-else-if="appStore.settings.Layout === 'horizontal'">
      <el-container class="main-container horizontal-layout">
        <el-header class="header">
          <Header />
        </el-header>
        <TabsView v-if="!appStore.settings.HideTabs" />
        <el-main ref="mainContentRef" class="main-content" @scroll="handleScroll">
          <div class="content-wrapper">
            <router-view v-slot="{ Component, route }">
              <transition name="fade-transform" mode="out-in">
                <keep-alive v-if="appStore.settings.KeepAlive" :include="cachedViews">
                  <component :is="Component" :key="route.path" />
                </keep-alive>
                <component v-else :is="Component" :key="route.path" />
              </transition>
            </router-view>
          </div>
        </el-main>
      </el-container>
    </template>

    <!-- 混合布局 - Logo + 左侧一级菜单 + 右侧二级菜单和内容 -->
    <template v-else-if="appStore.settings.Layout === 'mix'">
      <el-aside 
        v-if="!appStore.settings.HiddenSideBar" 
        :width="sidebarWidth" 
        class="sidebar-container"
      >
        <!-- Logo -->
        <div class="logo">
          <div class="logo-icon">
            <svg viewBox="0 0 24 24" fill="currentColor" class="logo-svg">
              <path d="M12 2L2 7v10c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V7l-10-5z"/>
            </svg>
          </div>
          <transition name="fade">
            <div v-if="appStore.sidebar.opened" class="logo-text">
              <span class="logo-title">{{ appStore.settings.Title }}</span>
              <span class="logo-subtitle">管理系统</span>
            </div>
          </transition>
        </div>
        <Sidebar />
      </el-aside>

      <el-container class="main-container mix-layout">
        <el-header class="header">
          <Header />
        </el-header>
        <TabsView v-if="!appStore.settings.HideTabs" />
        <div class="mix-content-wrapper">
          <!-- 二级菜单侧边栏 -->
          <el-aside v-if="secondaryMenuRoutes.length > 0" :width="'200px'" class="secondary-sidebar">
            <el-scrollbar class="secondary-scrollbar">
              <el-menu
                :default-active="activeSecondaryMenu"
                router
                class="secondary-menu"
              >
                <el-menu-item 
                  v-for="route in secondaryMenuRoutes" 
                  :key="route.path"
                  :index="route.path"
                >
                  <el-icon v-if="route.meta?.icon">
                    <component :is="getIconComponent(route.meta.icon)" />
                  </el-icon>
                  <span>{{ route.meta?.title }}</span>
                </el-menu-item>
              </el-menu>
            </el-scrollbar>
          </el-aside>
          
          <!-- 主内容区 -->
          <el-main ref="mainContentRef" class="main-content" @scroll="handleScroll">
            <div class="content-wrapper">
              <router-view v-slot="{ Component, route }">
                <transition name="fade-transform" mode="out-in">
                  <keep-alive v-if="appStore.settings.KeepAlive" :include="cachedViews">
                    <component :is="Component" :key="route.path" />
                  </keep-alive>
                  <component v-else :is="Component" :key="route.path" />
                </transition>
              </router-view>
            </div>
          </el-main>
        </div>
      </el-container>
    </template>
  </el-container>
</template>

<script setup>
import { ref, computed, watch, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useAppStore } from "@/store/app";
import { useTabsStore } from "@/store/tabs";
import Sidebar from "./Sidebar.vue";
import Header from "./Header.vue";
import TabsView from "./TabsView.vue";
import * as ElementPlusIconsVue from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const appStore = useAppStore();
const tabsStore = useTabsStore();
const mainContentRef = ref(null);

// 获取图标组件
const getIconComponent = (iconName) => {
  if (!iconName) return ElementPlusIconsVue.Document;
  const componentName = iconName
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join('');
  return ElementPlusIconsVue[componentName] || ElementPlusIconsVue.Document;
};

// 获取二级菜单路由（混合模式）
const secondaryMenuRoutes = computed(() => {
  if (appStore.settings.Layout !== 'mix') {
    return [];
  }
  
  const routes = router.getRoutes();
  const rootRoute = routes.find(r => r.path === '/');
  
  if (!rootRoute || !rootRoute.children) {
    return [];
  }
  
  const currentPath = route.path;
  let selectedParentMenu = null;
  
  // 查找包含当前路径的一级菜单
  for (const child of rootRoute.children) {
    if (currentPath === child.path || currentPath.startsWith(child.path + '/')) {
      selectedParentMenu = child;
      break;
    }
  }
  
  // 如果找到一级菜单且有子菜单，返回其子菜单
  if (selectedParentMenu && selectedParentMenu.children && selectedParentMenu.children.length > 0) {
    return selectedParentMenu.children.filter(child => !child.meta?.hidden);
  }
  
  return [];
});

// 获取激活的二级菜单
const activeSecondaryMenu = computed(() => route.path);

// 保存每个路由的滚动位置
const scrollPositions = ref({});

const sidebarWidth = computed(() => {
  return appStore.sidebar.opened ? "200px" : "64px";
});

// 需要缓存的组件名称列表（根据打开的页签动态计算）
const cachedViews = computed(() => {
  // 如果禁用了标签缓存，返回空数组
  if (!appStore.settings.MultiTagsCache) {
    return [];
  }
  return tabsStore.tabsList.map(tab => tab.name).filter(Boolean);
});

// 获取滚动容器元素
const getScrollElement = () => {
  if (!mainContentRef.value) return null;
  // el-main 组件，需要通过 $el 访问 DOM
  return mainContentRef.value.$el || mainContentRef.value;
};

// 监听滚动事件，保存当前路由的滚动位置
const handleScroll = () => {
  const scrollEl = getScrollElement();
  if (scrollEl) {
    scrollPositions.value[route.path] = {
      scrollTop: scrollEl.scrollTop,
      scrollLeft: scrollEl.scrollLeft
    };
  }
};

// 监听路由变化，恢复滚动位置
watch(() => route.path, async (newPath) => {
  await nextTick();
  
  // 延迟恢复，等待过渡动画完成
  setTimeout(() => {
    const scrollEl = getScrollElement();
    
    if (scrollEl) {
      if (scrollPositions.value[newPath]) {
        // 恢复之前保存的滚动位置
        const { scrollTop, scrollLeft } = scrollPositions.value[newPath];
        scrollEl.scrollTop = scrollTop;
        scrollEl.scrollLeft = scrollLeft;
      } else {
        // 新页面，滚动到顶部
        scrollEl.scrollTop = 0;
        scrollEl.scrollLeft = 0;
      }
    }
  }, 350); // 等待过渡动画完成（fade-transform 是 300ms）
}, { flush: 'post' });
</script>

<style scoped>
.layout-container {
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏容器 */
.sidebar-container {
  background: #ffffff;
  box-shadow: 2px 0 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  z-index: 10;
  border-right: 1px solid #e8eaed;
  overflow: hidden;
}

/* Logo 区域 */
.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 16px;
  gap: 12px;
  background: #ffffff;
  border-bottom: 1px solid #e8eaed;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.logo-icon {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #1a73e8;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(26, 115, 232, 0.2);
  flex-shrink: 0;
}

.logo-svg {
  width: 20px;
  height: 20px;
  color: #ffffff;
}

.logo-text {
  display: flex;
  flex-direction: column;
  gap: 2px;
  overflow: hidden;
}

.logo-title {
  font-size: 16px;
  font-weight: 600;
  color: #202124;
  letter-spacing: 0.3px;
  white-space: nowrap;
}

.logo-subtitle {
  font-size: 11px;
  color: #5f6368;
  white-space: nowrap;
}

/* 主容器 */
.main-container {
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

/* Header */
.header {
  background: #ffffff;
  box-shadow: 0 1px 3px rgba(60, 64, 67, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  position: relative;
  z-index: 9;
  border-bottom: 1px solid #e8eaed;
}

/* 主内容区 */
.main-content {
  background: transparent;
  padding: 20px;
  overflow-y: auto;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

/* Tooltip 样式优化 */
:deep(.el-tooltip__popper) {
  max-width: 200px;
}

/* 水平布局样式 */
.layout-horizontal .main-container {
  width: 100%;
}

.layout-horizontal .header {
  height: 64px;
}

/* 混合布局样式 */
.layout-mix .mix-content {
  flex: 1;
  display: flex;
}

.layout-mix .mix-content .sidebar-container {
  background: #ffffff;
  border-right: 1px solid #e8eaed;
}

.layout-mix .header-with-menu {
  height: 64px;
  display: flex;
  align-items: center;
}

/* 混合模式内容区域包装器 */
.mix-content-wrapper {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 二级菜单侧边栏样式 */
.layout-mix .secondary-sidebar {
  background: #ffffff;
  border-right: 1px solid #e8eaed;
  overflow: hidden;
  height: 100%;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.03);
}

.secondary-scrollbar {
  height: 100%;
  width: 100%;
}

.secondary-menu {
  border-right: none;
  background: transparent;
  height: 100%;
  padding: 8px 0;
}

.secondary-menu :deep(.el-menu-item) {
  color: #606266;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  margin: 2px 12px;
  padding: 0 16px !important;
  border-radius: 8px;
  height: 44px;
  line-height: 44px;
  font-size: 14px;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
  font-weight: 400;
}

/* 添加左侧激活指示条 */
.secondary-menu :deep(.el-menu-item::before) {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 0;
  background: var(--el-color-primary);
  border-radius: 0 2px 2px 0;
  transition: height 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.secondary-menu :deep(.el-menu-item:hover) {
  background: #f5f5f5 !important;
  color: #303133;
}

.secondary-menu :deep(.el-menu-item.is-active) {
  background: var(--el-color-primary) !important;
  color: #ffffff !important;
  font-weight: 500;
}

/* 激活状态隐藏左侧指示条 */
.secondary-menu :deep(.el-menu-item.is-active::before) {
  display: none;
}

.secondary-menu :deep(.el-menu-item .el-icon) {
  color: #909399;
  font-size: 18px;
  margin-right: 10px;
  transition: color 0.15s ease;
}

.secondary-menu :deep(.el-menu-item.is-active .el-icon) {
  color: #ffffff !important;
  transition: none;
}

.secondary-menu :deep(.el-menu-item:hover .el-icon) {
  color: #303133;
}
</style>
